package cn.leonis.leetcode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

/**
 * @Author Tobi
 * @Date 2021-07-12 下午5:45
 */
public class ReshapeMatrixSolution {

    public static void main(String[] args) {
        int[][] mat = new int[][]{{1, 2}, {3, 4}, {5, 6}, {7, 8}};
        ReshapeMatrixSolution solution = new ReshapeMatrixSolution();
        int[][] ints = solution.matrixReshape(mat, 4, 2);
        for (int i = 0; i < ints.length; i++) {
            for (int num: ints[i]) {
                System.out.println("num = " + num);
            }
        }
    }

    /**
     * 存在空指针异常
     * @param mat
     * @param r
     * @param c
     * @return
     */
    public int[][] matrixReshape(int[][] mat, int r, int c) {
        Queue<Integer> queue = new ArrayDeque<>();
        for (int i = 0; i < mat.length; i++) {
            for (int j = 0; j < mat[i].length; j++) {
                queue.add(mat[i][j]);
            }
        }
        int[][] result = new int[r][c];
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                result[i][j] = queue.poll();
            }
        }

        return result;
    }

    public int[][] matrixReshape1(int[][] mat, int r, int c) {
        int m = mat.length;
        int n = mat[0].length;
        if (m * n != r * c) {
            return mat;
        }
        int[][] ans = new int[r][c];
        for (int i = 0; i < m * n; i++) {
            ans[i / c][i % c] = mat[i / n][i % n];
        }

        return ans;
    }
}
